package com.dobest.base.random;

import org.junit.jupiter.api.Test;

import java.util.*;

/**
 * @author huangy
 * @description
 * @since 2022/10/11 17:58
 **/
public class RandomTest {

    private static final Random RANDOM = new Random();

    @Test
    public void randomProb() {
        List<Integer> weights = Arrays.asList(100, 20, 50, 0);
//        List<Integer> weights = Arrays.asList(10, 20, 30, 10, 20, 10, 20);
        int weightSum = weights.stream().mapToInt(Integer::intValue).sum();
        System.out.println("权重总和: " + weightSum);
        int randomNum = RANDOM.nextInt(weightSum);
        System.out.println("随机值： " + randomNum);
        //随机数字的结果
        int result = 0;
        for (Integer weight : weights) {
            randomNum = randomNum - weight;
            if (randomNum <= 0) {
                break;
            }
            result++;
        }
        System.out.println("随机结果: " + (result));
    }

    @Test
    public void randomNum() {
        int length = 100;
        for (int i = 0; i < length; i++) {
            System.out.println(RANDOM.nextInt(10));
        }
    }

    public static int generateNum(Set<Integer> indexes, int range) {
        int index = RANDOM.nextInt(range);
        if (indexes.contains(index)) {
            //如果已经产生过就继续产生
            return generateNum(indexes, range);
        } else {
            indexes.add(index);
            return index;
        }
    }

    public static void main(String[] args) {
        Set<Integer> indexes = new HashSet<>();
        int range = 1000;
        for (int i = 0; i < 1000; i++) {
            System.out.println(generateNum(indexes, range));
        }
    }

}
